<%@page import="javax.script.*, sun.org.mozilla.javascript.internal.*" %>
<%!

/**
 *  创建一个处理JavaScript的脚本引擎。避免重新创建服务对象，缓存之。
 */
public static ScriptEngine js_engine = new ScriptEngineManager().getEngineByExtension("js"); 

// 执行js公式  
// String sss = (String)engine.eval("jsonObj.results");
// NativeArray arr = (NativeArray)js_engine.eval("jsonObj.results");
// String sss = (String)obj.get("title", obj);


// JDK 6 的 Rhino 不支持 JSON.parse
// String sss = (String)js_engine.eval("JSON.parse+''");
// System.out.println(sss);

/**
 * 将POJO对象转换成JSON格式的字符串
 * http://will-turner.iteye.com/blog/1506416
 * http://www.myexception.cn/javascript/728974.html
 * @param obj
 * @return
 */
public static String parseObj(Object obj){
    if (obj == null) {
        return "";
    }
    Class clazz = obj.getClass();
    java.lang.reflect.Field[] fields = clazz.getDeclaredFields();
    
    StringBuilder buff = new StringBuilder();
    buff.append("{");

    for (java.lang.reflect.Field f : fields) {
        String fieldName; Object value;
        try{
            fieldName = f.getName();
            if(fieldName.indexOf("this$") != -1)continue;

            value = f.get(obj);
            
            //System.out.println(fieldName + "--------" + value);
            buff.append("\"");
            buff.append(fieldName);
            buff.append("\":");

            if(value==null){
                buff.append("\"\",");
                continue;
            }
            if(value instanceof Boolean){
                buff.append((Boolean)value);
                buff.append(",");
            }else if(value instanceof Number){
                buff.append((Number)value);
                buff.append(",");
            }else if(value instanceof Date){
                buff.append("\"");
                buff.append(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date)value));
                buff.append("\",");
            }else if(value instanceof Object[]){
                Object[] arr = (Object[])value;
                String str = "";
                
                for(int i = 0; i < arr.length; i++){
                    if(arr[i] instanceof String){
                        str += ("\"" + arr[i] + "\"").replace("\\", "\\\\");
                    }else{
                        str += parseObj(arr[i]);
                    }
                    
                    if(i != arr.length - 1)str += ",";
                }

                buff.append("[");
                buff.append(str);
                buff.append("]o");// ??????????????//
            }else{
                buff.append("\"");
                buff.append(value.toString().replace("\\", "\\\\"));
                buff.append("\",");
            }
            
        }catch(IllegalArgumentException e){
        }catch (IllegalAccessException e) {
        //e.printStackTrace();
        //}catch(java.lang.reflect.InvocationTargetException e) {
            //e.printStackTrace();
        }
    }

    if (buff.length() > 1) {
        buff = buff.deleteCharAt(buff.length() - 1);
    }
    buff.append("}");

    return buff.toString();
}

public void printErr(Exception error, String customErrMsg)throws IOException{
    resp.setContentType("application/json");
    
    final String _msg = String.format("发生异常。异常信息：%s %s %s", 
        error == null ? "" : error.getMessage(), 
        error == null ? "" : error.toString(), 
        customErrMsg == null ? "" : customErrMsg
    );

    respWriter.println(parseObj(new Object() {  
        public Boolean isOk = false;   
        public String msg = _msg;
    }));
    respWriter.flush();
}
public void printErr(Exception error)throws IOException{
    printErr(error, null);
}
public void printErr(String customErrMsg)throws IOException{
    printErr(null, customErrMsg);
}

// public void printOk(final String customMsg)throws IOException{
//     resp.setContentType("application/json");
  
//     respWriter.println(parseObj(new Object() {  
//         public Boolean isOk = true;   
//         public String msg = customMsg;
//         public Object[] result = {
//             new Object(){
//                 public Boolean isOk = false;
//             }, new Object()
//         };
//     }));
//     respWriter.flush();
// }

// 返回 适合 iframe 读取的接口
public void printOk(final String customMsg, final Object[] _result)throws IOException{
    resp.setContentType("application/json");

    String json = parseObj(new Object() {  
        public Boolean isOk = true;   
        public String msg = customMsg;
        public Object[] result = _result;
    });

    //System.out.println(json);

    respWriter.println(json);
    respWriter.flush();
}
public void printOk(final String customMsg, Object _result)throws IOException{
    Object[] arr = {_result};
    printOk(customMsg, arr);
}

public static HashMap<String, Object>[] getArr(NativeArray nativeArr)throws IOException{
    if(nativeArr == null)return new HashMap[0];
    
    Long len = nativeArr.getLength();
    
    HashMap<String, Object>[] arr  = new HashMap[len.intValue()];
    
    for (Object o : nativeArr.getIds()) {
        Integer index = (Integer) o;
        NativeObject nativeObj = (NativeObject)nativeArr.get(index, nativeArr);
        HashMap<String, Object> item = NativeObject2Hash(nativeObj);
        
        arr[index.intValue()] = item;
    }

    return arr;
}

public static HashMap<String, Object>[] getArr(Object obj)throws IOException{
    if(obj != null && !obj.equals("")){
        NativeArray _NativeArray = (NativeArray)obj;
        return getArr(_NativeArray);
    }else return new HashMap[0];// 写成 new HashMap<String, Object>[0] 报错
}

// JS 对象 转换到 Java Hash 对象
public static HashMap<String, Object> NativeObject2Hash(NativeObject obj){
    HashMap<String, Object> _data = new HashMap<String, Object>();
    if(obj == null)return null;
    // 遍历对象
    Object[] ids = obj.getAllIds();
    for (Object id : ids) {
        String newId = (String) id;
        _data.put(newId, obj.get(newId, obj));
        // System.out.println("\n" + newId);
    }
    return _data;
}
%>